import os.path

import requests
import pub_ssh
import pub_readconf
import pub_config


def xj_unix_os(server):
    # 执行命令
    results = {}
    # 静态写死
    # commands = [{"hostname": "hostname"},{"all_ip": "hostname -I"},{"runtime_days": "awk '{print $1}' /proc/uptime"}]
    rc = pub_readconf.ReadConf(os.path.join(pub_config.ROOT_PATH, 'conf/xunjian_item.yml'))
    commands = rc.read_yaml()['unix_os']
    print(commands)

    client = pub_ssh.SSHClient(server['hostname'], server['port'], server['username'], server['password'])
    client.conn()

    for command in commands:
        print("正在执行：", command)
        for k, v in command.items():
            # 秒改天
            if k == "runtime_days":
                days = float(float(client.run(v)['stdout']) / 86400)
                results[k] = f"{days:.2f}"
            else:
                results[k] = client.run(v)['stdout']

    # 判断是否有外网
    try:
        response = requests.get('https://myip.ipip.net/', timeout=3)
        if response.status_code == 200:
            print(response.text)
            results['wip'] = response.text
        else:
            results['wip'] = None
    except Exception as e:
        print(e)

    # print(json.dumps(results))
    return results
